<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 查询条件的投诉类型下拉框（已复用选项，无需改代码） -->
      <el-form-item label="投诉类型" prop="complaintStyle">
        <el-select
            v-model="queryParams.complaintStyle"
            placeholder="请选择投诉类型"
            style="width: 160px"
            clearable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in complaintStyleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增：投诉状态下拉框 -->
      <el-form-item label="投诉状态" prop="complaintStatus">
        <el-select
            v-model="queryParams.complaintStatus"
            placeholder="请选择投诉状态"
            style="width: 160px"
            clearable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in complaintStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['comComplaintTS:complaintYYY:add']"
        >我要投诉</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="complaintYYYList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="投诉类型" align="center" prop="complaintStyle" />
      <el-table-column label="投诉内容" align="center" prop="complaintInfo" />
      <!-- 修改投诉照片展示方式 -->
      <el-table-column label="投诉照片" align="center" prop="complaintPhoto">
        <template #default="scope">
          <div v-if="!scope.row.complaintPhoto" class="no-photo">无照片</div>
          <div v-else class="photo-list">
            <el-image
                v-for="(imgUrl, index) in getPhotoList(scope.row.complaintPhoto)"
                :key="index"
                :src="imgUrl"
                :preview-src-list="getPhotoList(scope.row.complaintPhoto)"
                class="photo-item"
                fit="cover"
                lazy
            />
          </div>
        </template>
      </el-table-column>
      <!-- 【修改1】投诉时间列调用格式化函数 -->
      <el-table-column label="投诉时间" align="center" prop="createTime">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="投诉状态" align="center" prop="complaintStatus">
        <template #default="scope">
          <el-tag :type="getComplaintStatusTagType(scope.row.complaintStatus)">
            {{ getComplaintStatusText(scope.row.complaintStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comComplaintTS:complaintYYY:edit']">修改</el-button>-->
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['comComplaintTS:complaintYYY:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改我要投诉对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="complaintYYYRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="投诉类型" prop="complaintStyle">
          <el-select v-model="form.complaintStyle" placeholder="请选择投诉类型" clearable>
            <el-option
                v-for="item in complaintStyleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投诉内容" prop="complaintInfo">
          <el-input v-model="form.complaintInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- 修改为图片上传组件 -->
        <el-form-item label="投诉照片" prop="complaintPhoto">
          <el-upload
              v-model:file-list="uploadFileList"
              :action="uploadUrl"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :before-upload="beforeUpload"
              list-type="picture-card"
              limit="1"
              :auto-upload="true"
              :headers="uploadHeaders"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="upload-tip">支持 JPG、PNG 格式，单张不超过 5MB，最多上传 1 张</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ComplaintYYY">
import { listComplaintYYY, getComplaintYYY, delComplaintYYY, addComplaintYYY, updateComplaintYYY } from "@/api/comComplaintTS/complaintYYY"
import { getToken } from '@/utils/auth' // 假设从auth工具获取token

const { proxy } = getCurrentInstance()

const complaintYYYList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const uploadFileList = ref([]) // 上传文件列表
// 替换原有的 uploadUrl 定义，直接对接若依file服务的上传接口
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/file/upload';
// 说明：若依前端项目中，VITE_APP_BASE_API 通常已配置为网关地址（如 http://localhost:8080）
// 最终拼接后的地址会自动变为：http://localhost:8080/file/upload，正好对应ruoyi-file的上传接口
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    complaintStyle: null,
    complaintInfo: null,
    complaintPhoto: null,
    complaintStatus: null
  },
  rules: {
    userId: [
      { required: true, message: "业主ID不能为空", trigger: "blur" }
    ],
    // 新增：投诉类型必填校验
    complaintStyle: [
      { required: true, message: "请选择投诉类型", trigger: "change" }  // trigger="change"：下拉框选择变化时触发
    ],
    // 新增：投诉内容必填校验
    complaintInfo: [
      { required: true, message: "请输入投诉内容", trigger: "blur" }  // trigger="blur"：输入框失去焦点时触发
    ],

  }
})

const { queryParams, form, rules } = toRefs(data)

// 上传请求头，携带token
const uploadHeaders = computed(() => {
  return {
    'Authorization': 'Bearer ' + getToken()
  }
})

/** 查询我要投诉列表 */
function getList() {
  loading.value = true
  listComplaintYYY(queryParams.value).then(response => {
    complaintYYYList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    complaintStyle: null,
    complaintInfo: null,
    complaintPhoto: null,
    createTime: null,
    complaintStatus: null
  }
  uploadFileList.value = [] // 清空上传文件列表
  proxy.resetForm("complaintYYYRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加我要投诉"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getComplaintYYY(_id).then(response => {
    form.value = response.data

    // 回显已有照片
    const photoList = getPhotoList(form.value.complaintPhoto)
    uploadFileList.value = photoList.map(url => ({
      uid: Date.now() + Math.random(),
      name: url.split('/').pop() || 'photo.jpg',
      url: url,
      status: 'success'
    }))

    open.value = true
    title.value = "修改我要投诉"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["complaintYYYRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateComplaintYYY(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addComplaintYYY(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除我要投诉编号为"' + _ids + '"的数据项？').then(function() {
    return delComplaintYYY(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comComplaintTS/complaintYYY/export', {
    ...queryParams.value
  }, `complaintYYY_${new Date().getTime()}.xlsx`)
}

// 投诉类型下拉框选项
const complaintStyleOptions = ref([
  { label: "保洁清洁问题（公共区域脏乱）", value: "保洁清洁问题" },
  { label: "安保管理问题（人员/车辆管控差）", value: "安保管理问题" },
  { label: "维修响应问题（水电/设施报修不处理）", value: "维修响应问题" },
  { label: "噪音扰民（装修/邻居/商业噪音）", value: "噪音扰民" },
  { label: "停车管理问题（车位被占/乱停车）", value: "停车管理问题" },
  { label: "费用问题（物业费/代收费用异议）", value: "费用问题" },
  { label: "邻里纠纷（占用公共空间/宠物扰民）", value: "邻里纠纷" },
  { label: "公共设施损坏（电梯/路灯/器材坏了）", value: "公共设施损坏" },
  { label: "其他问题", value: "其他问题" }
]);

// 处理照片URL列表
const getPhotoList = (photoStr) => {
  if (!photoStr) return [];
  return photoStr.split(',').filter(url => url);
};

// 上传前校验
const beforeUpload = (rawFile) => {
  // 校验格式
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isImage) {
    proxy.$modal.msgError('请上传 JPG 或 PNG 格式的图片');
    return false;
  }
  // 校验大小（5MB）
  const isLt5M = rawFile.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    proxy.$modal.msgError('图片大小不能超过 5MB');
    return false;
  }
  return true;
};

// 上传成功回调
const handleUploadSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    const imgUrl = response.url || response.data.url;
    // 拼接URL为字符串（多图用逗号分隔）
    form.value.complaintPhoto = form.value.complaintPhoto
        ? `${form.value.complaintPhoto = imgUrl}`
        : imgUrl;
  } else {
    proxy.$modal.msgError('图片上传失败，请重试');
    uploadFileList.value = uploadFileList.value.filter(item => item.uid !== uploadFile.uid);
  }
};

// 删除已上传文件回调
const handleUploadRemove = (uploadFile, uploadFiles) => {
  const imgUrl = uploadFile.response?.url || uploadFile.response?.data?.url;
  if (imgUrl) {
    const photoList = getPhotoList(form.value.complaintPhoto);
    const newPhotoList = photoList.filter(url => url !== imgUrl);
    form.value.complaintPhoto = newPhotoList.join(',');
  }
  uploadFileList.value = uploadFiles;
};

const getComplaintStatusText = (state) => {
  switch (state) {
    case 0: return '待处理';
    case 1: return '已处理';
    default: return '未知状态';
  }
};

const getComplaintStatusTagType = (state) => {
  switch (state) {
    case 1: return 'success';
    case 0: return 'danger';
    default: return 'warning';
  }
};

const complaintStatusOptions = ref([
  { label: "待处理", value: 0 },  // value需与数据库存储的状态值一致（数字类型）
  { label: "已处理", value: 1 }
]);

// 【新增1】时间格式化函数：将 2025-09-18 19:28:11 转为 2025年9月18日
const formatDate = (dateString) => {
  if (!dateString) return ''; // 处理空时间的情况
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从0开始，需+1
  const day = date.getDate();
  return `${year}年${month}月${day}日`;
};

getList()
</script>

<style scoped>
/* 表格照片样式 */
.photo-list {
  //display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.photo-item {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}
.no-photo {
  color: #999;
  font-size: 12px;
}

/* 上传组件样式 */
.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
.el-upload--picture-card {
  width: 80px;
  height: 80px;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}
</style>